package com.xmg.p2p.base.service.impl;

import com.xmg.p2p.base.domain.MailVerify;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.mapper.MailVerifyMapper;
import com.xmg.p2p.base.service.EmailService;
import com.xmg.p2p.base.service.UserinfoService;
import com.xmg.p2p.base.util.BidConst;
import com.xmg.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessageRemovedException;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

/**
 * @BelongsProject: jinrong-website
 * @BelongsPackage: com.xmg.p2p.base.service.impl
 * @author: Andy
 * @date: 2021.3.15 10:02
 * @Description: 邮箱业务的实现类
 * @since JDK 1.8
 */
@Service
public class EmailServiceimpl implements EmailService {
    // 简单的注入
    @Value("${mail.applicationUrl}")
    private String applicationUrl;
    @Value("${mail.host}")
    private String host;
    @Value("${mail.username}")
    private String username;
    @Value("${mail.password}")
    private String password;

    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private MailVerifyMapper mailVerifyMapper;


    /**
     * 发送验证邮箱的方法
     * @param email
     */
    public void sendVerifyEmail(String email) {
        // 判断当前用户是否绑定邮箱，
        //      如果绑定，就不做任何操作。
        //      如果没有绑定，需要发送验证邮件
        Userinfo current = userinfoService.getById(UserContext.getCurrent().getId());
        if (!current.getIsBindEmail()){
            // 生成一个UUID
            String uuid = UUID.randomUUID().toString();
            // 构造邮件内容并且发送
            StringBuffer content = new StringBuffer(100);
            content.append("这是验证邮件,点击<a href='").append(this.applicationUrl)
                    .append("bindEmail.do?uuid=").append(uuid)
                    .append("'>这里</a>,有效期是").append(BidConst.EMAIL_VALID_DAY).append("天！");
            System.err.println(email+","+content.toString());
            try {
                sendMail(email,content.toString());
                System.out.println("发送成功");
                // 发送成功后，创建一个MailVerify对象
                MailVerify mv = new MailVerify();
                mv.setLogininfoId(current.getId());
                mv.setEmail(email);
                mv.setUuid(uuid);
                mv.setSendTime(new Date());
                this.mailVerifyMapper.insert(mv);
                System.err.println(mv);
            }catch (Exception ex){
                throw new RuntimeException("发送验证邮件失败！");
            }
        }

    }

    /**
     * 发送邮件
     * @param email     邮箱账号
     * @param content   内容
     */
    private void sendMail(String email, String content)
            throws MessagingException {

        //发送html邮件
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        //设置服务器地址(自己搭建一个邮箱服务器)
        sender.setHost(host);
        //创建一个邮件消息
        MimeMessage msg = sender.createMimeMessage() ;
        MimeMessageHelper msgHelper = new MimeMessageHelper(msg, "utf-8");
        //设置收件人 寄件人 等邮件相关
        msgHelper.setTo(email);//谁接受这个邮件 QQ邮箱  收件人
        msgHelper.setFrom(username);//谁发送的这个邮件  寄件人
        msgHelper.setSubject("绑定邮箱验证邮件");
        //设置邮件内容
        msgHelper.setText(content.toString(),true); //true 表示启动html格式的邮件
        //设置发送准备
        sender.setUsername(username);
        sender.setPassword(password);
        //设置发送邮件功能的一些属性配置  超时配置  账户验证
        Properties prop =  new Properties() ;
        prop.put("mail.smtp.auth",true) ; //设置为true 让服务器进行认证账户和密码是否正确
        prop.put("mail.smtp.timeout", "25000") ;
        sender.setJavaMailProperties(prop);
        //发送邮件
        sender.send(msg);
    }
}
